package moduloAreas;

import conexion.ManejadorConexion;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Transaction;
import pojos.Areas;

/**
 *
 * @author Diego Andres Gomez Montesinos
 */
public class ManejadorAreas {
    
    ManejadorConexion manejadorConexion;
    
    public ManejadorAreas(ManejadorConexion manejadorDeConexion) {
        manejadorConexion = manejadorDeConexion;
    }

    public Areas getAreaPorId(int idArea) {
        return (Areas) manejadorConexion.session.load(Areas.class, idArea);
    }
    
    public List getFullAreas() {
        String query = "FROM Areas";
        List areas = manejadorConexion.ejecutaBusquedaHQL(query);
        for(int i = 0; i < areas.size(); i++) {
            Areas areaActual = (Areas) areas.get(i);
            if(areaActual.getIdArea() == -1) {
                areas.remove(i);
            }
        }
        return areas;
    }
    
    public boolean hayAreas() {
        return !getFullAreas().isEmpty();
    }
    
    public void creaYGuardaArea(String nombreArea, String nombreEncargado) {
        Transaction transaccion= manejadorConexion.session.beginTransaction();
        Areas nuevaArea = new Areas();
        nuevaArea.setNombreArea(nombreArea);
        nuevaArea.setEncargado(nombreEncargado);
        manejadorConexion.session.save(nuevaArea);
        transaccion.commit();
    }
    
    public void borraAreaPorId(int idArea) {
       boolean commit = false;
       Transaction transaction = manejadorConexion.session.beginTransaction();
       try
       {
         Query query = manejadorConexion.session.createQuery
         ( "DELETE FROM Areas a WHERE a.idArea = :id" );
         query.setInteger( "id", idArea );
         query.executeUpdate();
         commit = true;
       }
       finally{
         if(commit){
           transaction.commit();
         }else
           transaction.rollback();
       }
     }

}
